package com.svs.generator.controller;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.svs.common.annotation.Log;
import com.svs.common.base.AjaxResult;
import com.svs.common.enums.BusinessType;
import com.svs.common.support.Convert;
import com.svs.common.utils.StringUtils;
import com.svs.framework.web.BaseController;
import com.svs.framework.web.page.TableDataInfo;
import com.svs.generator.domain.BizColumn;
import com.svs.generator.domain.BizTable;
import com.svs.generator.domain.ColumnInfo;
import com.svs.generator.domain.TableInfo;
import com.svs.generator.helper.BizTableHelper;
import com.svs.generator.service.IGenService;
import com.svs.generator.service.impl.BizColumnService;
import com.svs.generator.service.impl.BizTableService;
import com.svs.generator.util.GenUtils;

/**
 * 代码生成 操作处理
 * 
 * @author dujianqiao
 */
@Controller
@RequestMapping("/tool/gen")
public class GenController extends BaseController {
	
	private String prefix = "gen";

	@Autowired
	IGenService genService;

	@Autowired
	BizTableService bizTableService;
	@Autowired
	BizColumnService bizColumnService;

	@RequiresPermissions("tool:gen:view")
	@GetMapping()
	public String gen() {
		return prefix + "/genList";
	}

	@RequiresPermissions("tool:gen:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(TableInfo tableInfo) {
		startPage();
		List<TableInfo> list = genService.selectTableList(tableInfo);
		int len = null != list ? list.size() : 0 ;
		for(int i=0 ;i < len ; i++ ) {
			TableInfo tab = list.get(i) ;
			BizTable biz = bizTableService.selectByPrimaryKey(tab.getTableName()) ;
			if(null != biz) {
				tab.setState(BizTableHelper.SYNCED);
			}
		}
		return getDataTable(list);
	}
	
	/**
	 * 弹框选择
	 * 
	 * @return
	 */
	@GetMapping("genDialog")
	public String genDialog() {
		return prefix + "/genDialog";
	}
	
	@PostMapping("/listData")
	@ResponseBody
	public TableDataInfo listData(TableInfo tableInfo) {
		startPage();
		List<TableInfo> list = genService.selectTableListWithNo(tableInfo);
		return getDataTable(list);
	}
	

	/**
	 * 生成代码
	 */
	@RequiresPermissions("tool:gen:code")
	@Log(title = "代码生成", businessType = BusinessType.GENCODE)
	@GetMapping("/genCode/{tableName}")
	public void genCode(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException {
		byte[] data = genService.generatorCode(tableName);
		response.reset();
		response.setHeader("Content-Disposition", "attachment; filename=\"svs.zip\"");
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");

		IOUtils.write(data, response.getOutputStream());
	}

	/**
	 * 批量生成代码
	 */
	@RequiresPermissions("tool:gen:code")
	@Log(title = "代码生成", businessType = BusinessType.GENCODE)
	@GetMapping("/batchGenCode")
	@ResponseBody
	public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
		String[] tableNames = Convert.toStrArray(tables);
		byte[] data = genService.generatorCode(tableNames);
		response.reset();
		response.setHeader("Content-Disposition", "attachment; filename=\"svs.zip\"");
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");

		IOUtils.write(data, response.getOutputStream());
	}
	
	
	
	/**
	 * 同步业务表
	 * @param response
	 * @param tables
	 * @throws IOException
	 */
	@GetMapping("/sync")
	@ResponseBody
	public AjaxResult sync( String name) {
		TableInfo tableInfo = genService.selectTableByName(name) ;
		List<ColumnInfo> columns = genService.selectTableColumnsByName(name) ;
		BizTable table = new BizTable() ;
		table.setName(tableInfo.getTableName());
		table.setEntityName(GenUtils.tableToJava(tableInfo.getTableName()));
		table.setCreateTime(new Date());
		table.setComments(tableInfo.getTableComment());
		table.setIdCata(BizTableHelper.ID_CATA_INCREMENT);
		table.setAuthor("杜建桥");
		table.setState(BizTableHelper.NOT_SYNC);
		table.setIsImport(BizTableHelper.IS_IMPORT);
		int len = null != columns ? columns.size() : 0 ;
		for(int i=0;i<len ;i++ ) {
			ColumnInfo columnInfo = columns.get(i) ;
			BizColumn col = new BizColumn() ;
			col.setTableName(name);
			col.setComments(columnInfo.getColumnComment());
			col.setName(columnInfo.getColumnName());
			col.setJdbcType(columnInfo.getColumnType());
			col.setIsPk(columnInfo.getIsPk());
			col.setSort(columnInfo.getSort());
			String attrName = StringUtils.convertToCamelCase(columnInfo.getColumnName());
			col.setJavaField(StringUtils.uncapitalize(attrName));
			String javaType = GenUtils.javaTypeMap.get(columnInfo.getDataType());
			col.setJavaType(javaType);
			Integer jdbcLength = GenUtils.counJDBCLen(columnInfo.getColumnType()) ;
			col.setJdbcLength(jdbcLength);
			col.setIsInsert(BizTableHelper.IS_INSERT);
			col.setIsEdit(BizTableHelper.IS_EDIT);
			col.setIsList(BizTableHelper.IS_LIST);
			col.setIsImport(BizTableHelper.IS_IMPORT);
			col.setInput(BizTableHelper.INPUT_INPUT);
			
			bizColumnService.save(col) ;
		}
		bizTableService.save(table) ;
		return success() ;
	}
	
	
}
